<template>
  <div>
    <el-card>
      <el-form :inline="true" class="form">
        <el-form-item label="职位搜索">
          <el-input placeholder="请输入职位关键字" v-model="keyword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!keyword" @click="search">
            搜索
          </el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button type="primary" icon="plus" @click="addRole">
        添加职位
      </el-button>
      <el-table border style="width: 100%" :data="allRole">
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column
          label="角色名称"
          align="center"
          prop="roleName"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" @click="setPermission(row)">
              分配
            </el-button>
            <el-button type="primary" size="small" @click="updateRole(row)">
              编辑
            </el-button>
            <el-popconfirm
              :title="`确认删除${row.roleName}吗？`"
              @confirm="removeRole(row.id)"
            >
              <template #reference>
                <el-button type="primary" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 7, 9, 11]"
      :background="true"
      layout="prev, pager, next,jumper,->,sizes,total"
      :total="total"
      @current-change="getHasRole"
      @size-change="getHasRole(1)"
    ></el-pagination>
    <!-- 添加职位与更新已有职位的结构 -->
    <el-dialog
      v-model="dialogVisible"
      :title="roleParams.id ? '添加角色' : '新增角色'"
    >
      <el-form label-width="80px" :model="roleParams" :rules="rules" ref="form">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            placeholder="请输入角色名称"
            v-model="roleParams.roleName"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 抽屉组件：分配职位的菜单权限与按钮的权限 -->
    <el-drawer v-model="drawer">
      <template #header>分配权限</template>
      <template #default>
        <el-tree
          ref="tree"
          :data="menuArr"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="selectArr"
          :props="defaultProps"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="handler">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue'
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqSetPermission,
  reqRemoveRole,
} from '@/api/acl/role'
import type {
  RoleData,
  Records,
  RoleResponseData,
  MenuList,
  MenuResponseData,
} from '@/api/acl/role/type'
import { ElMessage } from 'element-plus'

let pageNo = ref<number>(1)
let pageSize = ref<number>(5)
let total = ref<number>(0)
// 搜索职位的关键字
let keyword = ref<string>('')
// 存储全部已有的职位
let allRole = ref<Records>([])
// 控制对话框的显示与隐藏
let dialogVisible = ref<boolean>(false)
// 控制抽屉显示与隐藏
let drawer = ref<boolean>(false)
//准备一个数组:数组用于存储勾选的节点的ID(四级的)
let selectArr = ref<number[]>([])
// 收集新增岗位数据
let roleParams = reactive({
  id: 0,
  roleName: '',
})
// 获取form组件实例
let form = ref<any>()
// 存储用户权限的数据
let menuArr = ref<MenuList>([])
// 获取树形组件实例
let tree = ref<any>()

const getHasRole = async (pager = 1) => {
  // 修改当前页码
  pageNo.value = pager
  let result: RoleResponseData = await reqAllRoleList(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code == 200) {
    total.value = result.data.total
    allRole.value = result.data.records
  }
}

onMounted(() => {
  // 获取职位请求
  getHasRole()
})
// 搜索按钮的回调
const search = () => {
  getHasRole()
  keyword.value = ''
}
// 重置按钮的回调
const reset = () => {
  keyword.value = ''
  getHasRole()
}
// 添加职位按钮的回调
const addRole = () => {
  dialogVisible.value = true
  // 清空数据
  Object.assign(roleParams, {
    id: 0,
    roleName: '',
  })
  nextTick(() => form.value.clearValidate('roleName'))
}
// 更新已有职位按钮的回调
const updateRole = (row: RoleData) => {
  dialogVisible.value = true
  Object.assign(roleParams, row)
  nextTick(() => form.value.clearValidate('roleName'))
}
const validatorRoleName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('角色名称至少两位'))
  }
}
// 职位校验规则
const rules = {
  roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }],
}
// 确定按钮的回调
const save = async () => {
  await form.value.validate()
  let result: any = await reqAddOrUpdateRole(roleParams)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: roleParams.id ? '更新成功' : '添加成功',
    })
    dialogVisible.value = false
    getHasRole()
  } else {
    ElMessage({
      type: 'error',
      message: roleParams.id ? '更新失败' : '添加失败',
    })
    dialogVisible.value = false
  }
}
// 分配权限按钮的回调
const setPermission = async (row: RoleData) => {
  drawer.value = true
  // 收集当前分类权限的职位的数据
  Object.assign(roleParams, row)
  // 根据角色获取权限的数据
  let result: MenuResponseData = await reqAllMenuList(roleParams.id as number)
  if (result.code == 200) {
    menuArr.value = result.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
}
// 树形控件
const defaultProps = {
  children: 'children',
  label: 'name',
}

const filterSelectArr = (allData: any, initArr: any) => {
  // 从给定的多层级数据结构中筛选出满足条件的节点的 id 值，
  // 并将这些 id 值存入一个初始为空的数组 initArr 中。
  // 通过递归遍历每个节点及其子节点，它能够有效地处理复杂的嵌套数据结构，并提取符合指定条件的数据。
  allData.forEach((item: any) => {
    if (item.select && item.level == 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}
// 抽屉确定按钮的回调
const handler = async () => {
  // 职位ID
  let roleId = roleParams.id
  // 选中节点的ID
  let arr = tree.value.getCheckedKeys()
  // 未确定的id
  let arr1 = tree.value.getHalfCheckedKeys()
  let permissionId = arr.concat(arr1)
  let result: any = await reqSetPermission(roleId, permissionId)
  if (result.code == 200) {
    drawer.value = false
    ElMessage({ type: 'success', message: '分配权限成功' })
    window.location.reload()
  }
}
// 删除已有的职位
const removeRole = async (id: number) => {
  let result: any = await reqRemoveRole(id)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '删除成功' })
    getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-form-item {
    margin-bottom: 0px;
  }
}
</style>
